<!DOCTYPE html>
<html lang="en">
<head>
<title>3D.CITY destructor</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
html { width:100%; height:100%; }
body {  padding:0; margin: 0px; background:#6666e6; font:12px sans-serif; width:100%; height:100%; color:#fff; overflow: hidden;}
#debug{ position:absolute; padding:10px; right:0; bottom:0; text-align:right; width:20%; pointer-events:none; display:block; }
#log{ position:absolute; padding:10px; left:0; bottom:0; width:30%; pointer-events:none; display:block;}
#hub{ position:absolute; top:0; left:0; height:100%; width:100%; pointer-events:none; display:block; text-align:center;}
#top{ position:absolute; top:10px; left:10px; height:20px; width:100px; pointer-events:auto; cursor:pointer; display:block; text-align:center; font-size: 16px; background: #606060; padding: 10px;}
#destroy{ position:absolute; top:60px; left:10px; height:20px; width:100px; pointer-events:auto; cursor:pointer;  display:block; text-align:center; font-size: 16px; background: #404040; padding: 10px;}
#burn{ position:absolute; top:110px; left:10px; height:20px; width:100px; pointer-events:auto; cursor:pointer;  display:block; text-align:center; font-size: 16px; background: #cc4040; padding: 10px;}
</style>
<script src="js/three.min.js"></script>
<script src="js/sea3d.min.js"></script>
<script src="js/SPE.min.js"></script>
<script src="src3d/view3d.js"></script>

</head>
<body>
<div id="container"></div>
<div id="debug">pre alpha 0.76</div>
<div id="log">loth 2014</div>
<div id="hub"></div>
<div id="top">New building</div>
<div id="destroy">Destroy</div>
<div id="burn">Burn</div>
<script>
var l = document.getElementById('log');
var view3d;
var hub = null;
var obj = null;
var timestep = 1000/60;
var timer;
var time;
var maxDecal;
var posDecal;
var finalColor;
var ncolor = 1;
var reflectionCube;
var isDestroy = false;
var isBurn = false;
var objInfo;
var environment;
var ptex;
var emitter, particleGroup = null, atmosphereBurnEmitter;
var box;

var snd_destroy = new Audio("./sound/explosion-low.mp3");
var snd_destroy2 = new Audio("./sound/explosion-high.mp3");

window.onload = init;

function init(){
    view3d = new V3D.Base();
    document.getElementById('top').addEventListener('click',  function ( e ) {e.preventDefault(); newObject(); }, false);
    document.getElementById('destroy').addEventListener('click',  function ( e ) {e.preventDefault(); destroy(); }, false);
    document.getElementById('burn').addEventListener('click',  function ( e ) {e.preventDefault(); burning(); }, false);
}

function log(txt){ l.innerHTML = txt || '';  }

function start() {

    ptex = new THREE.TextureLoader().load( './img/smoke.png' );

	loop();

	view3d.center = new THREE.Vector3(0,1,0);
	view3d.cam.distance = 10;
	view3d.cam.vertical = 85;
    view3d.moveCamera();

	var c3 = document.createElement("canvas");
	ctx = c3.getContext("2d");
	c3.width = c3.height = 64;
	ctx.rect(0, 0, 64, 64);
    ctx.fillStyle = "#cc7f66";
	ctx.fill();

	environment = new THREE.Texture(c3, THREE.SphericalReflectionMapping );
	environment.needsUpdate = true;

	var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 30, 30 ), new THREE.MeshBasicMaterial( {color:0xcc7f66} ) );
	mesh.geometry.applyMatrix(new THREE.Matrix4().makeRotationX( - Math.PI / 2 ));
	view3d.scene.add( mesh );

    box = new THREE.Mesh( new THREE.BoxBufferGeometry( 1,1,1 ), new THREE.MeshBasicMaterial( {wireframe:true, color:0x000000, transparent:true, opacity:0.1} ) );
    box.geometry.applyMatrix(new THREE.Matrix4().makeTranslation( 0,0.5,0 ));
    view3d.scene.add( box );

	newObject();
}

function newObject() {
	if(obj !== null ){
		clearInterval(timer);
		obj.geometry.dispose();
		obj.material.dispose();
	    view3d.scene.remove(obj);
	}
	/*if(particleGroup){
		particleGroup.removeEmitter(emitter);
        particleGroup.removeEmitter(atmosphereBurnEmitter);
        emitter.reset();
        atmosphereBurnEmitter.reset();
        view3d.scene.remove( particleGroup.mesh );
	}*/

	obj = view3d.getRandomObject();
	view3d.scene.add(obj);

	obj.material.reflectivity = 0;
	obj.material.combine = THREE.MixOperation;
	obj.material.envMap = environment;
	//obj.material.side = THREE.DoubleSide;

	//obj.geometry.computeBoundingBox();
	//var box = obj.geometry.boundingBox;
	objInfo = [0, 0];//[Number(box.max.y.toFixed(2)), ,  Number((box.max.x + Math.abs(box.min.x)).toFixed(2)),  Number((box.max.z + Math.abs(box.min.z)).toFixed(2)), obj.geometry.attributes.position.array.length / 3 ];

    //obj.geometry.computeBoundingSphere()
    findSize( obj.geometry );
    //console.log(objInfo)

	if(objInfo[1] == 4) posDecal = 0.5;
	else if(objInfo[1] == 6) posDecal = 1.5;
	else posDecal = 0; 

    box.position.set(posDecal, 0, -posDecal);

	view3d.center = new THREE.Vector3( posDecal, 0.5, -posDecal );

	view3d.moveCamera();


	log("name:" + obj.name  + " y: " + objInfo[0] + " x: " + objInfo[1] );

	isDestroy = false;
	isBurn = false;
}

function findSize( g ){

    var xmax = -100;
    var xmin = 100;
    var zmax = 0;
    var zmin = 0;
    var ymax = 0;

    var i, v, r, n;
    v = obj.geometry.attributes.position.array;
    i = v.length / 3;

    while(i--){
        n = i*3;

        xmax = Math.max(v[n], xmax);
        xmin = Math.min(v[n], xmin);

        ymax = Math.max(v[n+1], ymax);
        //zmin = Math.min(v[n+2], zmin);

        zmax = Math.max(v[n+2], zmax);
        zmin = Math.min(v[n+2], zmin);

    }

    var sx = -xmin + xmax;
    var sz = -zmin + zmax;
    var sy = ymax;

    objInfo[0] = Number(sy.toFixed(2));
    objInfo[1] = Math.round(sx);
    //objInfo[3] = sz;

    box.scale.set(sx, sy, sz)

    //console.log(xmax, xmin, ymax, zmax, zmin)
}

function burning() {
	if(!isBurn && !isDestroy){
		isBurn = true;

		time = 5;
		maxDecal = Math.abs((objInfo[0]/time)*17);
		
		if(timer) clearInterval(timer);
		timer = setInterval(destroyCycle, timestep);

		initParticles();

		snd_destroy.play();

	}
}


function destroy() {
	if(!isDestroy && !isBurn ){

		isDestroy = true;

		time = 1;
		maxDecal = Math.abs((objInfo[0]/time)*15);
	    //console.log(maxDecal)

		if(timer)clearInterval(timer);
		timer = setInterval(destroyCycle, timestep);

		initParticles();

		snd_destroy2.play();
    }
}

function destroyCycle() {
	//var vec = obj.geometry.vertices;
	
	//var maxDecal = Math.abs((objInfo[0]*100)/time);

	if(isBurn){

	}

	//var i = obj.geometry.faces.length; 
	//obj.geometry.vertices.length;

	var i, v, r, n;

	/*while(i--){
		r = randRange(0, 20);
		f = obj.geometry.faces[i];
		if (vec[f.a].y > 0 ) vec[f.a].y -=r/1000;
		if (vec[f.b].y > 0 ) vec[f.b].y -=r/1000;
		if (vec[f.c].y > 0 ) vec[f.c].y -=r/1000;
	}*/

    v = obj.geometry.attributes.position.array;
    i = v.length / 3;

	
	while(i--){
        n = i*3;
       // v = vertex[n+1];
		r = randRange(1, maxDecal);

       // v*=0.9;

        //vertex[n+1]*=0.9



		if (v[n+1] > 0.02 ) v[n+1]-=r/1000;
		else v[n+1] = 0.02;
	}

	//var color = obj.material.color.getHex();
	//if(color>0x000000)
	//obj.material.color.lerp(finalColor, ncolor);//.setHex(color-0x010101);
	//obj.material.color.lerp("black", 0.01);
	if(obj.material.reflectivity<1) obj.material.reflectivity+=0.005/time;

	//obj.geometry.computeFaceNormals();
    //obj.geometry.computeVertexNormals();
	//obj.geometry.verticesNeedUpdate = true;

    obj.geometry.attributes.position.needsUpdate = true

}
function randRange(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}
function burn() {

}

function loop() {
    requestAnimationFrame( loop );//, view3d.renderer.domElement );
    if( particleGroup !== null) particleGroup.tick( 0.016 );
    view3d.renderer.render( view3d.scene, view3d.camera );
}





function initParticles() {

    if( particleGroup !== null ){
        particleGroup.removeEmitter( emitter );
        particleGroup.removeEmitter(atmosphereBurnEmitter);
        emitter.reset();
        atmosphereBurnEmitter.reset();
        view3d.scene.remove( particleGroup.mesh );

        particleGroup = null;
    }

	var height = objInfo[0];
	var size = objInfo[1];
	var duration = time;
	var nParticule = Math.round(( height + size)*10);//+(objInfo[4]/4));

	var acc = 0.5 + height*0.5;

    var colors = [0xFFFFFF, 0x808080 ,0x000000];

	var colors = ['white','gray','black'];
	var pSize = [0.5, 5, 0];
	
	if(isBurn){
        colors = [0x00FFFF,0xFFFF00,0xFF0000]
		//colors = ['blue','yellow','red'];
		pSize = [0.5, 10, 0];
		duration +=2;
		acc = 1+ height*0.5;
	}


    particleGroup = new SPE.Group({
        maxParticleCount:nParticule*2,
        texture: {
                    value: ptex
                },//THREE.ImageUtils.loadTexture('img/.png'),
        //maxAge: 2,
        //depthWrite: false,
        //depthTest: false,
        //transparent: true,
        //nParticule*2,
    });



    //emitter.enable();
    emitter = new SPE.Emitter({

        particleCount: nParticule,

        type: SPE.distributions.BOX,

        //maxAge: duration,
        duration: duration*1.5,
        //size: { value: 1 },
        //radius: size,
        radius:{ value:size },

        position:{ 
            value :new THREE.Vector3( posDecal, 0, -posDecal ),
            spread: new THREE.Vector3( size*0.8, height , size*0.8 ),
        },
        acceleration: {
            value: new THREE.Vector3(0, acc, 0),
            spread: new THREE.Vector3( 0, 0, 0 )
        },
        velocity: {
            value: new THREE.Vector3(0, 0, 0),
            spread: new THREE.Vector3( 0, 0, 0 )
        },
        color: {
            value: [ new THREE.Color(colors[0]), new THREE.Color(colors[1]), new THREE.Color(colors[2]) ],
            spread: new THREE.Vector3(0, 0, 0),
        },
        size: { value: pSize, spread: new THREE.Vector3(0, 0.2, 0)  },
        opacity: { value: [0, 0, 1], spread: new THREE.Vector3(0.3, 1, 0) },

        /*
        velocity: new THREE.Vector3(0, 0, 0),
        velocitySpread: new THREE.Vector3(0, 0, 0),

        // Color tests
        colorStart: new THREE.Color( colors[0] ),
        colorStartSpread: new THREE.Vector3(0, 0, 0),

        colorMiddle: new THREE.Color( colors[1] ),
        colorMiddleSpread: new THREE.Vector3(0, 0, 0),

        colorEnd: new THREE.Color( colors[2] ),
        colorEndSpread: new THREE.Vector3(0, 0, 0),

        // Size tests
        sizeStart: pSize[0],
        sizeStartSpread: 0,

        sizeMiddle: pSize[1],
        sizeMiddleSpread: 0.2,

        sizeEnd: pSize[2],
        sizeEndSpread: 0,

        // Opacity tests
        opacityStart: 0,
        opacityStartSpread: 0,
        
        opacityMiddle: 0,
        opacityMiddleSpread: 1,

        opacityEnd: 1,
        opacityEndSpread: 0,*/

        

        //duration: duration

        // Angle tests
        // angleStart: Math.PI * 0.5,
        // angleStartSpread: Math.PI * 2,

        // angleMiddle: 0,
        // angleMiddleSpread: Math.PI * 2,

        // angleEnd: Math.PI * 1.5,
        // angleEndSpread: Math.PI * 1.5
    });


    atmosphereBurnEmitter = new SPE.Emitter({
        particleCount: nParticule,
        duration: duration*1.5,
        type: SPE.distributions.BOX,
        radius:{value:size},
        position:{ 
            value :new THREE.Vector3(posDecal, 0, -posDecal ),
            spread:new THREE.Vector3( size, 1, size ),
        },
        acceleration: {
            value:  new THREE.Vector3( 0, acc/5, 0 ),
            spread: new THREE.Vector3( 1, 0, 0 )
        },
        size: { value: [0.1] },
    });

   // 

   particleGroup.addEmitter( emitter );
   particleGroup.addEmitter( atmosphereBurnEmitter );

   view3d.scene.add( particleGroup.mesh );

}

        
</script>
</body>
</html>